package router

import (
	"chat_gin/common/middleware"
	"chat_gin/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func Router() *gin.Engine {
	r := gin.Default()
	r.GET("/", service.GetIndex)
	r.GET("/users", service.GetUserList)
	r.GET("/new_user", service.CreateUser)
	r.GET("/del_user", service.DelUser)
	r.GET("/edit_user", service.ChangeUser)

	// 处理跨域问题
	cors := r.Group("/cors")
	cors.Use(middleware.Cors())
	{
		cors.GET("/users", service.GetUserList)
		cors.OPTIONS("/users", service.GetUserList)

		// 登录接口
		cors.GET("/login", service.Login)
		cors.OPTIONS("/login", service.Login)
	}

	// 登录接口
	r.POST("/login", service.Login)
	r.OPTIONS("/login", service.Login)
	// 注册接口
	r.POST("/reg", service.Reg)

	// 使用路由组和中间件进行鉴权
	auth := r.Group("/api")
	auth.Use(middleware.JwtToken())
	{
		auth.GET("/users", service.GetUserList) // 访问 /api/users 就会鉴权
		auth.GET("/new_user", service.CreateUser)
		auth.GET("/del_user", service.DelUser)
		auth.GET("/edit_user", service.ChangeUser)
	}

	// 发送消息
	r.GET("/send", service.SendMsg)
	r.GET("/send2", service.SendUserMsg)

	err := r.Run(viper.GetString("server.HttpPort"))
	if err != nil {
		fmt.Println("gin启动失败", err)
		return nil
	}
	return r
}
